<template>
  <div class="region-statistics">
    <!-- 权限范围提示 -->
    <el-alert
      v-if="!isSuperAdmin && userDataScope.length > 0"
      :title="`数据权限范围：${getDataScopeText()}`"
      type="info"
      :closable="false"
      show-icon
      class="permission-alert"
    />
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon size="32" color="#409eff"><LocationInformation /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">区域总数</div>
              <div class="card-value">{{ statistics.totalRegions }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon size="32" color="#67c23a"><OfficeBuilding /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">社区总数</div>
              <div class="card-value">{{ statistics.totalCommunities }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon size="32" color="#e6a23c"><House /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">楼栋总数</div>
              <div class="card-value">{{ statistics.totalBuildings }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon size="32" color="#f56c6c"><User /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">房户总数</div>
              <div class="card-value">{{ statistics.totalHouseholds }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="父区域">
          <el-select v-model="filterForm.parentId" placeholder="选择父区域" clearable @change="handleFilterChange">
            <el-option label="全部区域" :value="null" />
            <el-option 
              v-for="region in filteredRegionOptions" 
              :key="region.id" 
              :label="region.regionName" 
              :value="region.id || 0" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleFilterChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-container">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>区域人口统计</span>
              <el-button type="primary" size="small" @click="exportPopulationChart">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
          </template>
          <div ref="populationChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>社区分布统计</span>
              <el-button type="primary" size="small" @click="exportCommunityChart">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
          </template>
          <div ref="communityChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="charts-container">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>楼栋房户趋势统计</span>
              <el-button type="primary" size="small" @click="exportTrendChart">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>区域面积热力图</span>
              <el-button type="primary" size="small" @click="exportHeatmapChart">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
          </template>
          <div ref="heatmapChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
/**
 * 区域统计页面
 * @author Wu.Liang
 * @date 2025-01-21
 * @updated 2025-06-29 - 添加物业公司权限控制和数据权限过滤
 */
import { ref, reactive, onMounted, nextTick, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { LocationInformation, House, User, Download, Refresh, OfficeBuilding } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { regionApi, type PopulationStats, type CommunityDistribution, type BuildingHouseholdTrend, type AreaHeatmap } from '@/api/region'
import { useUserStore } from '@/store/user'
import { 
  isSuperAdmin, 
  getUserDataScope, 
  getUserPropertyCompanyId
} from '@/utils/permission'

// 用户store
const userStore = useUserStore()

// 权限相关计算属性
const isSuperAdminUser = computed(() => isSuperAdmin())
const userDataScope = computed(() => getUserDataScope())
const userPropertyCompanyId = computed(() => getUserPropertyCompanyId())
const isPropertyCompanyUserFlag = computed(() => userStore.isPropertyCompanyUser)

// 响应式数据
const loading = ref(false)
const statistics = ref({
  totalRegions: 0,
  totalCommunities: 0,
  totalBuildings: 0,
  totalHouseholds: 0,
  occupancyRate: 0,
  communityDistribution: [],
  buildingDistribution: [],
  householdDistribution: []
})

// 筛选条件
const filterForm = reactive({
  parentId: null as number | null,
  dateRange: [] as string[]
})

// 区域选项
const regionOptions = ref<Array<{id: number, regionName: string}>>([])

// 根据权限过滤的区域选项
const filteredRegionOptions = computed(() => {
  if (isSuperAdminUser.value) {
    return regionOptions.value
  }
  
  // 物业公司用户只能看到有权限的区域
  if (isPropertyCompanyUserFlag.value && userDataScope.value.length > 0) {
    return regionOptions.value.filter(region => 
      userDataScope.value.includes(region.id.toString())
    )
  }
  
  return regionOptions.value
})

// 图表数据
const populationData = ref<PopulationStats[]>([])
const communityData = ref<CommunityDistribution[]>([])
const trendData = ref<BuildingHouseholdTrend[]>([])
const heatmapData = ref<AreaHeatmap[]>([])

// 图表引用
const populationChartRef = ref()
const communityChartRef = ref()
const trendChartRef = ref()
const heatmapChartRef = ref()

// 图表实例
let populationChart: echarts.ECharts | null = null
let communityChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null
let heatmapChart: echarts.ECharts | null = null

// 获取数据权限范围文本
const getDataScopeText = () => {
  if (isSuperAdminUser.value) {
    return '全部数据'
  }
  
  if (isPropertyCompanyUserFlag.value) {
    const companyId = userPropertyCompanyId.value
    if (companyId) {
      return `物业公司ID: ${companyId}`
    }
  }
  
  if (userDataScope.value.length > 0) {
    return `社区: ${userDataScope.value.join(', ')}`
  }
  
  return '无权限数据'
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    loading.value = true
    
    // 构建查询参数，包含权限过滤
    const params: any = {}
    if (!isSuperAdminUser.value && userPropertyCompanyId.value) {
      params.propertyCompanyId = userPropertyCompanyId.value
    }
    if (!isSuperAdminUser.value && userDataScope.value.length > 0) {
      params.communityIds = userDataScope.value.join(',')
    }
    
    const response = await regionApi.getRegionStatistics(params)
    if (response.code === 200) {
      // 确保数据格式正确
      const data = response.data || {}
      statistics.value = {
        totalRegions: data.totalRegions || 0,
        totalCommunities: data.totalCommunities || 0,
        totalBuildings: data.totalBuildings || 0,
        totalHouseholds: data.totalHouseholds || 0,
        occupancyRate: data.occupancyRate || 0,
        communityDistribution: Array.isArray(data.communityDistribution) ? data.communityDistribution : [],
        buildingDistribution: Array.isArray(data.buildingDistribution) ? data.buildingDistribution : [],
        householdDistribution: Array.isArray(data.householdDistribution) ? data.householdDistribution : []
      }
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage({ type: 'error', message: '加载统计数据失败' } as any)
  } finally {
    loading.value = false
  }
}

// 加载区域选项
const loadRegionOptions = async () => {
  try {
    const response = await regionApi.getRegionTree()
    if (response.code === 200 && response.data) {
      console.log('原始区域数据:', response.data)
      
      // 过滤掉id为null或undefined的区域，确保数据完整性
      const validRegions = response.data.filter((region: any) => {
        const isValid = region && 
                       region.id != null && 
                       region.id !== undefined && 
                       region.id !== '' &&
                       region.regionName && 
                       region.regionName.trim() !== ''
        
        if (!isValid) {
          console.warn('发现无效区域数据:', region)
        }
        
        return isValid
      })
      
      regionOptions.value = validRegions.map((region: any) => ({
        id: Number(region.id), // 确保id是数字类型
        regionName: region.regionName.trim()
      }))
      
      console.log('处理后的区域选项:', regionOptions.value)
    } else {
      console.warn('区域数据响应异常:', response)
      regionOptions.value = []
    }
  } catch (error) {
    console.error('加载区域选项失败:', error)
    ElMessage({ type: 'error', message: '加载区域选项失败' } as any)
    regionOptions.value = []
  }
}

// 加载人口统计数据
const loadPopulationData = async () => {
  try {
    // 构建查询参数，包含权限过滤
    const params: any = {}
    if (filterForm.parentId) {
      params.parentId = filterForm.parentId
    }
    if (!isSuperAdminUser.value && userPropertyCompanyId.value) {
      params.propertyCompanyId = userPropertyCompanyId.value
    }
    if (!isSuperAdminUser.value && userDataScope.value.length > 0) {
      params.communityIds = userDataScope.value.join(',')
    }
    
    const response = await regionApi.getPopulationStats(params)
    if (response.code === 200) {
      populationData.value = response.data || []
      initPopulationChart()
    }
  } catch (error) {
    ElMessage({ type: 'error', message: '加载人口统计数据失败' } as any)
  }
}

// 加载社区分布数据
const loadCommunityData = async () => {
  try {
    // 构建查询参数，包含权限过滤
    const params: any = {}
    if (filterForm.parentId) {
      params.parentId = filterForm.parentId
    }
    if (!isSuperAdminUser.value && userPropertyCompanyId.value) {
      params.propertyCompanyId = userPropertyCompanyId.value
    }
    if (!isSuperAdminUser.value && userDataScope.value.length > 0) {
      params.communityIds = userDataScope.value.join(',')
    }
    
    const response = await regionApi.getCommunityDistribution(params)
    if (response.code === 200) {
      communityData.value = response.data || []
      initCommunityChart()
    }
  } catch (error) {
    ElMessage({ type: 'error', message: '加载社区分布数据失败' } as any)
  }
}

// 加载趋势数据
const loadTrendData = async () => {
  try {
    // 构建查询参数，包含权限过滤
    const params: any = {}
    if (filterForm.parentId) {
      params.regionId = filterForm.parentId
    }
    if (filterForm.dateRange?.length === 2) {
      params.startDate = filterForm.dateRange[0]
      params.endDate = filterForm.dateRange[1]
    }
    if (!isSuperAdminUser.value && userPropertyCompanyId.value) {
      params.propertyCompanyId = userPropertyCompanyId.value
    }
    if (!isSuperAdminUser.value && userDataScope.value.length > 0) {
      params.communityIds = userDataScope.value.join(',')
    }
    
    const response = await regionApi.getBuildingHouseholdTrend(params)
    if (response.code === 200) {
      trendData.value = response.data || []
      initTrendChart()
    }
  } catch (error) {
    ElMessage({ type: 'error', message: '加载趋势数据失败' } as any)
  }
}

// 加载热力图数据
const loadHeatmapData = async () => {
  try {
    // 构建查询参数，包含权限过滤
    const params: any = {}
    if (filterForm.parentId) {
      params.parentId = filterForm.parentId
    }
    if (!isSuperAdminUser.value && userPropertyCompanyId.value) {
      params.propertyCompanyId = userPropertyCompanyId.value
    }
    if (!isSuperAdminUser.value && userDataScope.value.length > 0) {
      params.communityIds = userDataScope.value.join(',')
    }
    
    const response = await regionApi.getAreaHeatmap(params)
    if (response.code === 200) {
      heatmapData.value = response.data || []
      await initHeatmapChart()
    }
  } catch (error) {
    ElMessage({ type: 'error', message: '加载热力图数据失败' } as any)
  }
}

// 初始化人口统计图表（柱状图）
const initPopulationChart = () => {
  if (!populationChartRef.value) return
  if (populationChart) populationChart.dispose()
  populationChart = echarts.init(populationChartRef.value)
  
  const option = {
    title: {
      text: '区域人口统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: populationData.value?.map(item => item.regionName) || [],
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '人口数量'
    },
    series: [
      {
        name: '人口数量',
        type: 'bar',
        data: populationData.value?.map(item => item.population) || [],
        itemStyle: {
          color: '#409eff'
        }
      }
    ]
  }
  
  populationChart.setOption(option)
}

// 初始化社区分布图表（饼图）
const initCommunityChart = () => {
  if (!communityChartRef.value) return
  if (communityChart) communityChart.dispose()
  communityChart = echarts.init(communityChartRef.value)
  
  const option = {
    title: {
      text: '社区分布统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '社区分布',
        type: 'pie',
        radius: '50%',
        data: communityData.value?.map(item => ({
          name: item.regionName,
          value: item.communityCount
        })) || [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  communityChart.setOption(option)
}

// 初始化趋势图表（折线图）
const initTrendChart = () => {
  if (!trendChartRef.value) return
  if (trendChart) trendChart.dispose()
  trendChart = echarts.init(trendChartRef.value)
  
  const option = {
    title: {
      text: '楼栋房户趋势统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['楼栋数', '房户数'],
      top: '10%'
    },
    xAxis: {
      type: 'category',
      data: trendData.value?.map(item => item.date) || []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '楼栋数',
        type: 'line',
        data: trendData.value?.map(item => item.buildingCount) || [],
        smooth: true,
        itemStyle: {
          color: '#67c23a'
        }
      },
      {
        name: '房户数',
        type: 'line',
        data: trendData.value?.map(item => item.householdCount) || [],
        smooth: true,
        itemStyle: {
          color: '#e6a23c'
        }
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 初始化热力图图表（修正版，异步加载china.json并注册地图）
const initHeatmapChart = async () => {
  if (!heatmapChartRef.value) return

  // 1. 销毁已有实例，防止重复初始化
  if (heatmapChart) {
    heatmapChart.dispose()
  }

  // 2. 异步加载china.json并注册地图
  try {
    // 检查是否已注册china地图，避免重复注册
    if (!echarts.getMap('china')) {
      const response = await fetch('/static/map/china.json')
      if (!response.ok) throw new Error('地图数据加载失败')
      const geoJson = await response.json()
      echarts.registerMap('china', geoJson)
    }
  } catch (e) {
    ElMessage({ type: 'error', message: '中国地图GeoJSON加载失败' } as any)
    return
  }

  // 3. 初始化实例
  heatmapChart = echarts.init(heatmapChartRef.value)

  // 4. 配置option
  const option = {
    title: {
      text: '区域面积热力图',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params: any) {
        return `${params.data.regionName}<br/>面积: ${params.data.area}㎡<br/>热力值: ${params.data.heatValue}`
      }
    },
    visualMap: {
      min: 0,
      max: 100,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '5%',
      inRange: {
        color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffcc', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
      }
    },
    series: [
      {
        name: '区域面积',
        type: 'scatter',
        coordinateSystem: 'geo',
        data: heatmapData.value?.map(item => ({
          name: item.regionName,
          value: [item.longitude, item.latitude, item.heatValue],
          area: item.area,
          heatValue: item.heatValue,
          regionName: item.regionName
        })) || [],
        symbolSize: function(val: any) {
          return val[2] / 10 + 5
        },
        itemStyle: {
          color: function(params: any) {
            const heatValue = params.data.heatValue
            const colors = ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffcc', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
            const index = Math.floor(heatValue / 10)
            return colors[Math.min(index, colors.length - 1)]
          }
        }
      }
    ],
    geo: {
      map: 'china',
      roam: true,
      emphasis: {
        label: {
          show: false
        }
      }
    }
  }

  // 5. 设置option
  heatmapChart.setOption(option)
}

// 筛选条件变化处理
const handleFilterChange = () => {
  loadPopulationData()
  loadCommunityData()
  loadTrendData()
  loadHeatmapData()
}

// 刷新数据
const refreshData = () => {
  loadStatistics()
  loadPopulationData()
  loadCommunityData()
  loadTrendData()
  loadHeatmapData()
  ElMessage({ type: 'success', message: '数据刷新成功' } as any)
}

// 导出图表
const exportPopulationChart = () => {
  if (populationChart) {
    const url = populationChart.getDataURL()
    downloadChart(url, '区域人口统计图.png')
  }
}

const exportCommunityChart = () => {
  if (communityChart) {
    const url = communityChart.getDataURL()
    downloadChart(url, '社区分布统计图.png')
  }
}

const exportTrendChart = () => {
  if (trendChart) {
    const url = trendChart.getDataURL()
    downloadChart(url, '楼栋房户趋势统计图.png')
  }
}

const exportHeatmapChart = () => {
  if (heatmapChart) {
    const url = heatmapChart.getDataURL()
    downloadChart(url, '区域面积热力图.png')
  }
}

// 下载图表
const downloadChart = (url: string, filename: string) => {
  const link = document.createElement('a')
  link.download = filename
  link.href = url
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage({ type: 'success', message: '导出成功' } as any)
}

// 初始化所有图表
const initCharts = async () => {
  await nextTick()
  initPopulationChart()
  initCommunityChart()
  initTrendChart()
  await initHeatmapChart()
}

// 监听窗口大小变化
const handleResize = () => {
  populationChart?.resize()
  communityChart?.resize()
  trendChart?.resize()
  heatmapChart?.resize()
}

// 组件挂载
onMounted(async () => {
  await loadRegionOptions()
  await loadStatistics()
  await loadPopulationData()
  await loadCommunityData()
  await loadTrendData()
  await loadHeatmapData()
  await initCharts()
  window.addEventListener('resize', handleResize)
})

// 组件卸载
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  populationChart?.dispose()
  communityChart?.dispose()
  trendChart?.dispose()
  heatmapChart?.dispose()
})
</script>

<style lang="scss" scoped>
.region-statistics {
  padding: 20px;
  
  .permission-alert {
    margin-bottom: 20px;
  }
  
  .statistics-cards {
    margin-bottom: 20px;
    
    .statistics-card {
      .card-content {
        display: flex;
        align-items: center;
        
        .card-icon {
          margin-right: 16px;
        }
        
        .card-info {
          .card-title {
            font-size: 14px;
            color: var(--el-text-color-secondary);
            margin-bottom: 8px;
          }
          
          .card-value {
            font-size: 24px;
            font-weight: bold;
            color: var(--el-text-color-primary);
          }
        }
      }
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .charts-container {
    margin-bottom: 20px;
    
    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .chart-container {
        height: 300px;
        width: 100%;
      }
    }
  }
}
</style> 